<?php

/**
 * home actions.
 *
 * @package    Wildlive
 * @subpackage home
 * @author     Maximilian Lenkeit <dev@lenki.com>
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class homeActions extends sfActions
{

  /**
   * Executes index action
   *
   * @param sfRequest $request A request object
   */
  public function executeIndex (sfWebRequest $request)
  {
    ini_set('max_execution_time', 90);
    $data = $this->loadData();
    $first_set = current($this->data);
    $this->keys = array_keys($first_set);
  }

  public function executeMigrate (sfWebRequest $request)
  {
    ini_set('max_execution_time', 90);
    $conn = $this->getContext()
      ->getDatabaseConnection('doctrine');
    //$conn->beginTransaction();
    

    $data = $this->loadData();
    foreach ($data as $r)
    {
      if ($r['vorname'] == '' || $r['nachname'] == '' || $r['stamm_id'] == 0)
      {
        continue;
      }
      
      array_walk($r, 'test_alter');
      
      $member = new Member();
      $member->setOldMemberId($r['member_id']);
      $member->setFirstName($r['vorname']);
      $member->setLastName($r['nachname']);
      $member->setGender($r['maennlich'] == 1 ? 'male' : 'female');
      $member->save();
      
      $od = $member->getOrganizationalData();
      $woggle_id = $this->mapWoggle($r['knotenschild_id']);
      if ($woggle_id === false)
      {
        $this->getLogger()
          ->warning(sprintf('Invalid woggle id %s for member id %s', $r['knotenschild_id'], $r['member_id']));
      }
      else
      {
        $od->setWoggleId($woggle_id);
      }
      $age_group_id = $this->mapAgeGroup($r['stufen_id']);
      if ($age_group_id === false)
      {
        $this->getLogger()
          ->warning(sprintf('Invalid age group id %s for member id %s', $r['stufen_id'], $r['member_id']));
      }
      else
      {
        $od->setAgeGroupId($age_group_id);
      }
      $unit_id = $this->mapUnit($r);
      if ($unit_id === false)
      {
        $this->getLogger()
          ->warning(sprintf('Invalid unit id %s for member id %s', $r['gruppen_id'], $r['member_id']));
      }
      else
      {
        $od->setOrganizationalUnitId($unit_id);
      }
      if ($r['tstmpEintritt'] > 0)
      {
        $joining = date('Y-m-d', $r['tstmpEintritt']);
        $od->setDateOfJoining($joining);
      }
      if ($r['status'] == 0 && $r['tstmpAustritt'] > 0)
      {
        $resignation = date('Y-m-d', $r['tstmpEintritt']);
        $od->setDateOfResignation($resignation);
      }
      $od->setScarf(($r['halstuch'] == 1 ? true : false));
      $od->save();
      
      $pd = $member->getPersonalData();
      $pd->setEmailAddress($r['mail']);
      if ($r['tstmpGeburtsdatum'] > 0)
      {
        $birthday = $r['tstmpGeburtsdatum'] + 86400;
        $pd->setDateOfBirth(date('Y-m-d', $birthday));
      }
      $pd->setBirthplace($r['geburtsort']);
      $pd->setDirectDebitAuthorization(($r['konto_lastschrift'] == 1 ? true : false));
      $pd->save();
      
      if (strlen($r['konto_inhaber']) > 0)
      {
        $ba = $pd->getBankAccount();
        $ba->setOwner($r['konto_inhaber']);
        $ba->setNumber($r['konto_nummer']);
        $ba->setBankCode($r['konto_blz']);
        $ba->setBank($r['konto_institut']);
        $ba->save();
        $pd->setBankAccount($ba);
        $pd->save();
      }
      
      if (strlen($r['strasse']) > 0)
      {
        $ad = new Address();
        $t = explode(' ', $r['strasse']);
        $street_number = array_pop($t);
        $street = implode(' ', $t);
        $ad->setStreet($street);
        $ad->setStreetNumber($street_number);
        $ad->setZipCode($r['plz']);
        $ad->setCity($r['ort']);
        if ($r['land'] == 'DE')
        {
          $ad->setCountryId(1);
        }
        $ad->save();
        $link = new MemberAddress();
        $link->setAddress($ad);
        $link->setPersonalMemberData($pd);
        $link->save();
      
   //        $pd->getAddresses()->add($ad);
      //        $pd->getAddresses()->save();
      //        $pd->save();
      }
      
      if (strlen($r['fon_vorwahl']) > 0 && strlen($r['fon']) > 0)
      {
        $pn = new PhoneNumber();
        $pn->setAreaCode($r['fon_vorwahl']);
        $pn->setCallThrough($r['fon']);
        $pn->setType('landline');
        $pn->save();
        $member->attachPhoneNumber($pn);
        $member->save();
      }
      
      if (strlen($r['fon2_vorwahl']) > 0 && strlen($r['fon2']) > 0)
      {
        $pn = new PhoneNumber();
        $pn->setAreaCode($r['fon2_vorwahl']);
        $pn->setCallThrough($r['fon2']);
        $pn->setType('landline');
        $pn->save();
        $member->attachPhoneNumber($pn);
        $member->save();
      }
      
      if (strlen($r['fax_vorwahl']) > 0 && strlen($r['fax']) > 0)
      {
        $pn = new PhoneNumber();
        $pn->setAreaCode($r['fax_vorwahl']);
        $pn->setCallThrough($r['fax']);
        $pn->setType('fax');
        $pn->save();
        $member->attachPhoneNumber($pn);
        $member->save();
      }
      
      if (strlen($r['mobil_vorwahl']) > 0 && strlen($r['mobil']) > 0)
      {
        $pn = new PhoneNumber();
        $pn->setAreaCode($r['mobil_vorwahl']);
        $pn->setCallThrough($r['mobil']);
        $pn->setType('mobil');
        $pn->save();
        $member->attachPhoneNumber($pn);
        $member->save();
      }
      
      if ($r['status'] == 0)
      {
        $this->getLogger()
          ->alert(sprintf('Delete %s', $r['member_id']));
        $member->delete();
      }
    }
  
   //$this->redirect($this->generateUrl('homepage'));
  }

  private function loadData ()
  {
    $this->config = $this->getContext()
      ->getConfiguration();
    $file_contents = file_get_contents($this->config->getRootDir() . '\\' . 'export.data');
    $this->data = unserialize($file_contents);
    return $this->data;
  }

  private function mapWoggle ($in)
  {
    if ($in >= 1 && $in <= 6)
    {
      return $in;
    }
    elseif ($in == 0)
    {
      return false;
    }
    else
    {
      return false;
    }
  }

  private function mapUnit ($in)
  {
    $offset = 0;
    $mapping = array(
      1 => 7, 2 => 5, 3 => 6, 4 => 13, 5 => 12, 6 => 11, 7 => 18, 8 => 17, 17 => 9, 23 => 10, 24 => 14, 25 => 4, 26 => 16, 27 => 15);
    if (isset($mapping[$in['gruppen_id']]))
    {
      return $mapping[$in['gruppen_id']] + $offset;
    }
    else
    {
      $mapping = array(
        1 => 8, 2 => 3, 3 => 16);
      if (isset($mapping[$in['stamm_id']]))
      {
        return $mapping[$in['stamm_id']] + $offset;
      }
      else
      {
        return false;
      }
    }
  }

  private function mapAgeGroup ($in)
  {
    if ($in >= 1 && $in <= 5)
    {
      return $in;
    }
    else
    {
      return false;
    }
  }

  public function executeImportGwve (sfWebRequest $request)
  {
    $conn = MemberTable::getInstance()->getConnection();
    $conn->beginTransaction();
    try
    {
      $this->config = $this->getContext()
        ->getConfiguration();
      $file_contents = file_get_contents($this->config->getRootDir() . '\\' . 'GWvE_Mitglieder_2012.csv');
      $file_contents = utf8_encode($file_contents);
      $this->rows = explode("\n", $file_contents);
      $this->members = array();
      $ids = array();
      foreach ($this->rows as $i => $row)
      {
        $this->rows[$i] = str_getcsv($row);
        if ($i == 0 || $i == 35)
          continue;
        $data = str_getcsv($row);
        if ($data[0] == 'Olemgbe')
          $data[0] = 'Olembge';
        $coll = MemberTable::getInstance()->findByLastNameAndFirstName($data[0], $data[1]);
        if (count($coll) > 0)
        {
          $member = $coll->getLast();
        }
        else
        {
          $member = new Member();
        }
        $this->members[$i] = $member;
        if ($member->isNew())
        {
        
        }
        else
        {
          if($member->isDeleted()) {
            $this->getLogger()->err($member->getId());
          }
          $ids[] = $member->getId();
          // Address
          $address = $member->getFirstAddress();
          $t = explode(' ', $data[6]);
          $street_number = array_pop($t);
          $street = implode(' ', $t);
          $address->setStreet($street);
          $address->setStreetNumber($street_number);
          $address->setZipCode($data[7]);
          $address->setCity($data[8]);
          $address->save();
          
          $od = $member->getOrganizationalData();
          $od->setDateOfJoining($this->transformDate($data[5]));
          $od->save();
          
          $pd = $member->getPersonalData();
          $pd->setBirthplace($data[15]);
          if ($data[3] != '')
            $pd->setDirectDebitAuthorization(1);
          else
            $pd->setDirectDebitAuthorization(0);
          $pd->setDateOfBirth($this->transformDate($data[14]));
          $pd->setEmailAddress($data[13]);
          $pd->save();
          
          $fee = new MembershipFeePayment();
          $fee->setYear(2012);
          $fee->setMemberId($od->getId());
          $fee->setAmount(substr($data[4], 0, 2));
          if($data[2] != '') {
            $fee->setDateOfPayment($this->transformDate($data[2]));
            $fee->setReference('Überweisung');
          } else {
            $fee->setDateOfPayment($this->transformDate($data[3]));
            $fee->setReference('Lastschrift');
          }
          //$fee->save();
          
          $phone = false; $phone2 = false; $fax = false; $mobile = false;
          $phone_numbers = $member->getPhoneNumbers();
          foreach($phone_numbers as $phone_number) {
            switch($phone_number->getType()) {
              case 'fax':
                if($data[10]) {
                  $d = $this->splitPhone($data[10]);
                  $phone_number->setAreaCode($d[0]);
                  $phone_number->setCallThrough($d[1]);
                  $phone_number->save();
                } else {
                  $phone_number->delete();
                }
                $fax = true;
                break;
              case 'mobile':
                if($data[11]) {
                  $d = $this->splitPhone($data[11]);
                  $phone_number->setAreaCode($d[0]);
                  $phone_number->setCallThrough($d[1]);
                  $phone_number->save();
                } else {
                  $phone_number->delete();
                }
                $mobile = true;
                break;
              case 'landline':
              default:
                if($phone != true) {
                  if($data[9]) {
                    $d = $this->splitPhone($data[9]);
                    $phone_number->setAreaCode($d[0]);
                    $phone_number->setCallThrough($d[1]);
                    $phone_number->setType('landline');
                    $phone_number->save();
                  } else {
                    $phone_number->delete();
                  }
                  $phone = true;
                } elseif($phone2 != true) {
                  if($data[12]) {
                    $d = $this->splitPhone($data[12]);
                    $phone_number->setAreaCode($d[0]);
                    $phone_number->setCallThrough($d[1]);
                    $phone_number->setType('landline');
                    $phone_number->save();
                  } else {
                    $phone_number->delete();
                  }
                  $phone2 = true;
                }
                break;
                
            }
          }
          $pn_to_enter = array(9 => $phone, 10 => $fax, 11 => $mobile, 12 => $phone2);
          foreach($pn_to_enter as $k => $r) {
            if($r == true || $data[$k] == '') continue;
            $d = $this->splitPhone($data[$k]);
            $pn = new PhoneNumber();
            $pn->setAreaCode($d[0]);
            $pn->setCallThrough($d[1]);
            $pn->setType(($k == 9 || $k == 12 ? 'landline' : ($k == 10 ? 'fax' : 'mobile')));
            $pn->save();
            $l = new MemberPhoneNumber();
            $l->setMemberId($pd->getId());
            $l->setPhoneNumberId($pn->getId());
            $l->save();
          }
        }
      }
      $all_members = OrganizationalUnitTable::getInstance()->findOneByName('Stamm Graf Wolff von Eberstein')->retrieveMembers();
      foreach($all_members as $m) {
        if(!in_array($m->getId(), $ids)) {
          $m->delete();
          $this->getLogger()->alert('deleting '.$m->getFirstName(). ' '.$m->getLastName() );
        }
      } 
      //$conn->commit();
      $conn->rollback();
    }
    catch (Exception $e)
    {
      $conn->rollback();
      throw $e;
    }
  }

  private function transformDate ($in)
  {
    $t = explode('.', $in);
    return sprintf('%s-%s-%s', $t[2], $t[1], $t[0]);
  }
  
  private function splitPhone($in) {
    $in = str_replace(' ', '', $in);
    $in = str_replace('+49', '0', $in);
    $area_code = substr($in, 0, 5);
    $call_through = substr($in, 5);
    return array($area_code, $call_through);
  }
}

function test_alter (&$item1, $key)
{
  $item1 = utf8_encode($item1);
}
